﻿using Microsoft.Extensions.ObjectPool;
using EssentialWebFramework.Models.Framework;
using RabbitMQChannel = RabbitMQ.Client.IModel;
using RabbitMQConnection = RabbitMQ.Client.IConnection;
using RabbitMQConnectionFactory = RabbitMQ.Client.ConnectionFactory;

namespace EssentialWebFramework.Library.RabbitMQ
{
    /// <summary>
    /// 池化 RabbitMQChannel 的策略
    /// </summary>
    public class PooledRabbitMQModelPolicy : PooledObjectPolicy<RabbitMQChannel>
    {
        /// <summary>
        /// 
        /// </summary>
        // TODO 应改为使用单例模式
        private RabbitMQConnectionFactory _connectionFactory;

        private RabbitMQConnection _connection;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="amqpConfig"></param>
        public PooledRabbitMQModelPolicy(GlobalConfig.AMQPCfg amqpConfig)
        {
            _connectionFactory = new RabbitMQConnectionFactory
            {
                HostName = GlobalConfig.Setting.AMQP.HostName,
                Port = GlobalConfig.Setting.AMQP.Port,
                UserName = GlobalConfig.Setting.AMQP.UserName,
                Password = GlobalConfig.Setting.AMQP.Password,
                VirtualHost = GlobalConfig.Setting.AMQP.VirtualHost
            };

            Console.WriteLine("调用了 Policy 的构造方法");

            _connection = _connectionFactory.CreateConnection();
        }

        /// <summary>
        /// Create
        /// </summary>
        /// <returns></returns>
        public override RabbitMQChannel Create()
        {
            return _connection.CreateModel();
        }

        /// <summary>
        /// Return
        /// </summary>
        /// <param name="channel"></param>
        /// <returns></returns>
        public override bool Return(RabbitMQChannel channel)
        {
            if (channel.IsOpen)
            {
                return true;
            }
            else
            {
                channel?.Dispose();
                return false;
            }
        }
    }
}
